package com.collection.web.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.collection.api.entity.sys.SysResource;
import com.collection.api.entity.sys.SysRole;
import com.collection.api.sys.SysResourceService;
import com.collection.api.sys.SysRoleService;
import com.collection.web.pagination.Page;
import com.collection.web.pagination.PageBuilder;
import com.collection.web.pagination.PageRequest;
import com.collection.web.resolver.annotation.GridParam;
import com.collection.web.shiro.Menu;
import com.collection.web.shiro.util.TreeNodeUtil;

import net.sf.json.JSONArray;

/**
 * @descrption:角色管理
 * @author :HanDiYan
 * @Date : 2017年12月27日
 **/
@Controller
@RequestMapping("/role")
public class SysRoleController {
	
	private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);
	
	@Reference(version="1.0.0")
	SysRoleService sysRoleService;
	
	@Reference(version="1.0.0")
	private SysResourceService  sysResourceService;
	
	private String errorCode = "";
	private String errorMessage="";
	Map<String,Object> map = new HashMap<String,Object>();
	
	/**
	 * 角色列表页面
	 */
	@RequestMapping("/index")
	public String index(String roleName,String userType,@GridParam PageRequest pageRequest,
											HttpServletRequest request){
		logger.info("-------------------进入角色管理列表接口-------------------");
		List<Map<String, Object>> sysrole = sysRoleService.findRoleList(roleName, userType, 
												pageRequest.getOffset(),pageRequest.getPageSize());
		int total = sysRoleService.countRoleList(roleName, userType);
		Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, sysrole, total);
		request.setAttribute("page", page);
		request.setAttribute("total", page.getTotalPages());
		request.setAttribute("sysrole", sysrole);
		logger.info("-------------------跳转角色管理list-------------------");
		return "sys/role/list";
	}
	
	/**
	 * 进入新增角色页面
	 */
	@RequestMapping("/add")
	public String add(HttpServletRequest request){
		List<Map<String, Object>> sysResourceTreeList =  sysResourceService.findAllResource();
   	 	request.setAttribute("sysResourceTreeList", JSONArray.fromObject(sysResourceTreeList).toString());
		return "sys/role/add";
	}
	
	
	/**
	 * 保存新增的角色
	 * @return
	 */
	@RequestMapping(value="/save", method = RequestMethod.POST )
	@ResponseBody
	public Object save(Integer roleId ,@RequestParam(required=true) String userName, Integer appId,String userType,String ids){
		List<String> resourceIds =new ArrayList<String>();
		try {
			CollectionUtils.addAll(resourceIds, StringUtils.split(ids, ","));
			if(roleId==null){
				sysRoleService.insertSelective(userName, userType,  appId, resourceIds);
			}else{
				sysRoleService.updateByPrimaryKeySelective(roleId, userName, userType, appId, resourceIds);
			}
			errorCode = "1";
			errorMessage = "保存成功!";
			map.put("errorCode", errorCode);
			map.put("errorMessage", errorMessage);
			logger.error("========================保存角色成功========================");
			return map;
		} catch (Exception e) {
			logger.error("保存失败",e);
			errorCode = "1";
			errorMessage = "保存失败!";
			map.put("errorCode", errorCode);
			map.put("errorMessage", errorMessage);
			return map;
		}
		
	}
	
	@RequestMapping("/getResources")
	@ResponseBody
	public Object getResources(Integer roleId,Integer appId){
		if(roleId==null){
			return TreeNodeUtil.getfatherNode(sysRoleService.findAllResource());
		}else{
			return getfatherNode(sysRoleService.findResourcesByRoleId(roleId,appId));	
		}
	}
	 public final static List<Menu> getfatherNode(List<Map<String, Object>> treeDataList) {
         List<Menu> newTreeDataList = new ArrayList<Menu>();
         for (Map<String, Object> resource: treeDataList) {
             if( ((Integer)resource.get("parentId")).intValue() ==  0 ) {
                 
                 Menu menu =new Menu(Integer.valueOf(resource.get("id").toString()),resource.get("name").toString(),StringUtils.replace(resource.get("url")==null?"":resource.get("url").toString(), "**", ""), (Integer)resource.get("sort"),   null);
                 menu.setChecked(NumberUtils.toInt(resource.get("checked").toString())==1?true:false);
                 
                 //获取父节点下的子节点
                 menu.setChildren(getChildrenNode((Integer)resource.get("id"),treeDataList));
                 
                 newTreeDataList.add(menu);
             }
         }
         return newTreeDataList;
     }
	 
	 private final static List<Menu> getChildrenNode(Integer pid , List<Map<String, Object>> treeDataList) {
         List<Menu> newTreeDataList = new ArrayList<Menu>();
         for (Map<String, Object> resource:  treeDataList) {
             if(Integer.valueOf(resource.get("parentId").toString()).intValue()  ==  0)  continue;
             //这是一个子节点
             if(((Integer)resource.get("parentId")).intValue() == pid.intValue()){
                 
                 Menu menu =new Menu(Integer.valueOf(resource.get("id").toString()),resource.get("name").toString(),StringUtils.replace(resource.get("url")==null?"":resource.get("url").toString(), "**", ""), (Integer)resource.get("sort"),   null);
                 menu.setChecked(NumberUtils.toInt(resource.get("checked").toString())==1?true:false);
                 //递归获取子节点下的子节点
                 menu.setChildren(getChildrenNode(Integer.valueOf(resource.get("id").toString()) , treeDataList));
                 newTreeDataList.add(menu);
             }
         }
         return newTreeDataList;
     }
	 
	 
	    /**
		 * 进入编辑角色页面
		 * @param roleId
		 * @param request
		 * @return
		 */
	 @RequestMapping("/edit")
     public String edit(Integer roleId,HttpServletRequest request){
    	 SysRole sysRole = sysRoleService.selectByPrimaryKey(roleId);
    	 List<Map<String, Object>> sysResourceTreeList =  sysResourceService.findAllSelectedResource();
    	 request.setAttribute("sysResourceTreeList", JSONArray.fromObject(sysResourceTreeList).toString());
         request.setAttribute("role", sysRole);
         return "sys/role/edit";
     }
	 
		
		/**
		 * 根据角色id删除角色
		 */
		@RequestMapping("/delete")
		@ResponseBody
		public Object delete(@RequestParam(required=true)Integer roleId,HttpServletRequest request){
			int size=sysRoleService.countUserByRoleId(roleId);
			if(size>0){
				errorCode = "1";
				errorMessage = "该角色已有绑定用户,请先解绑";
				map.put("errorCode", errorCode);
				map.put("errorMessage", errorMessage);
				return map;
			}
			try {
				sysRoleService.delRoleByRoleId(roleId);
				errorCode = "1";
				errorMessage = "删除成功";
				map.put("errorCode", errorCode);
				map.put("errorMessage", errorMessage);
				return map;
			} catch (Exception e) {
				logger.error("{} 角色已有绑定用户,请先解绑",roleId,e);
				errorCode = "1";
				errorMessage = "该角色已有绑定用户,请先解绑";
				map.put("errorCode", errorCode);
				map.put("errorMessage", errorMessage);
				return map;
			}
		}
		
		
		/**
		 * 查询所有的角色
		 * @return
		 */
		@RequestMapping("/combox")
	    @ResponseBody
	    public List<SysRole> combox(){
	        return sysRoleService.findRoleListAll();
	    }
	 

}
